package org.tio.sitexxx.service.tool;

import java.sql.Date;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.sitexxx.service.vo.Const;
import org.tio.utils.SystemTimer;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

/**
 * @author tanyw
 *
 */
public class MysqlTool {
	private static Logger log = LoggerFactory.getLogger(MysqlTool.class);

	/**
	 * 
	 */
	public MysqlTool() {

	}

	/**
	 * 将表移入历史表
	 * @param dbName
	 * @param tableName
	 * @return
	 */
	public static void toHistory(String dbName, String tableName) {
		Db.use(dbName).tx(new IAtom() {

			@Override
			public boolean run() throws SQLException {
				String createSql = showCreateSql(dbName, tableName);
				String tempTableName = tableName + "_temp";
				String tempCreatSql = StrUtil.replace(createSql, "CREATE TABLE `" + tableName + "`", "CREATE TABLE `" + tempTableName + "`");

				log.warn("开始创建临时表\r\n{}", tempCreatSql);
				Db.use(dbName).update(tempCreatSql);

				String newTableName = tableName + "_" + DateUtil.format(new Date(SystemTimer.currTime), "yyyyMMddHHmm") + Const.HistoryTable.HISTORY_TABLE_SUFFIX;
				String renameSql = "RENAME TABLE " + tableName + " to " + newTableName + ", " + tempTableName + " to " + tableName;
				log.warn("开始重命名表\r\n{}", renameSql);

				Db.use(dbName).update(renameSql);

				return true;
			}

		});

	}

	/**
	 * 显示创建表结构的SQL脚本
	 * @param dbName
	 * @param tableName
	 * @return
	 */
	public static String showCreateSql(String dbName, String tableName) {
		String sql = "show create table " + tableName;
		Record record = Db.use(dbName).findFirst(sql);
		String ct = record.getStr("Create Table");
		return ct;
	}

}
